package com.road.vast.interceptor;

import com.road.vast.common.entity.ResultCode;
import com.road.vast.common.exception.CommonException;
import com.road.vast.component.JwtTokenComponent;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 郭泽鹏
 * @Date 2020/7/30 13:37
 * @Version 1.0
 * @Description jwt拦截器：判断是否已经登录
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    JwtTokenComponent jwtToken;

    /**
     * 简化获取token数据的代码编写（判断是否登录）
     * 1.通过request获取请求token信息
     * 2.从token中解析获取claims
     * 3.将claims绑定到request域中
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.通过request获取请求token信息
        String authorization = request.getHeader("Authorization");

        //判断请求头信息是否为空，或者是否已Bearer开头
        if (!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer")){
            //获取token数据
            String token = authorization.replace("Bearer ","");
            //解析token获取claims
            Claims claims = jwtToken.getJwtUtils().parseJwt(token);
            if(claims != null) {
                request.setAttribute("user_claims", claims);
                return true;
            }
        }
        throw new CommonException(ResultCode.UNAUTHENTICATED);
    }
}
